package mylog

import (
	"io/ioutil"
	stlog "log"
	"net/http"
	"os"
)

type fileLog string

//实现fileLog的Writer接口
func (fl fileLog) Write(date []byte) (int, error) {
	f, err := os.OpenFile(string(fl), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
	if err != nil {
		return 0, err
	}
	defer f.Close()
	return f.Write(date)
}

//日志实例
var localLog *stlog.Logger

//确定日志启动函数
func SetLog(destination string) {
	localLog = stlog.New(fileLog(destination), "[go] - :", stlog.LstdFlags)
}

//http请求相应函数
func RegisterHandlers() {
	http.HandleFunc("/mylog", func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodPost:
			msg, err := ioutil.ReadAll(r.Body)
			if err != nil || len(msg) == 0 {
				w.WriteHeader(http.StatusBadRequest)
				return
			} //只有非空的post请求才会写入
			write(string(msg))
		default:
			w.WriteHeader(http.StatusMethodNotAllowed)
			return
		}
	})
}

//日志写入函数
func write(message string) {
	localLog.Printf("%v\n", message)
}
